#!/bin/bash

# 数据一致性检查测试脚本
# 用于测试主从节点数据一致性检查和修复功能

set -e

echo "=========================================="
echo "MinFS 数据一致性检查测试脚本"
echo "=========================================="

# 配置
LEADER_HOST="localhost"
LEADER_PORT="8080"
FOLLOWER1_HOST="localhost"
FOLLOWER1_PORT="8081"
FOLLOWER2_HOST="localhost"
FOLLOWER2_PORT="8082"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 辅助函数
print_step() {
    echo -e "${BLUE}[步骤] $1${NC}"
}

print_success() {
    echo -e "${GREEN}[成功] $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}[警告] $1${NC}"
}

print_error() {
    echo -e "${RED}[错误] $1${NC}"
}

# 检查节点是否在线
check_node_online() {
    local host=$1
    local port=$2
    local name=$3
    
    if curl -s "http://${host}:${port}/admin/health" > /dev/null; then
        print_success "${name} 节点在线"
        return 0
    else
        print_error "${name} 节点离线"
        return 1
    fi
}

# 获取节点数据摘要
get_data_summary() {
    local host=$1
    local port=$2
    local name=$3
    
    echo -e "\n${BLUE}获取 ${name} 节点数据摘要:${NC}"
    curl -s "http://${host}:${port}/admin/data-summary" | jq '.'
}

# 执行一致性检查
perform_consistency_check() {
    echo -e "\n${BLUE}执行全集群数据一致性检查:${NC}"
    curl -s -X POST "http://${LEADER_HOST}:${LEADER_PORT}/admin/consistency-check" | jq '.'
}

# 获取同步状态
get_sync_status() {
    local host=$1
    local port=$2
    local name=$3
    
    echo -e "\n${BLUE}获取 ${name} 同步状态:${NC}"
    curl -s "http://${host}:${port}/admin/sync-status" | jq '.'
}

# 重置从节点数据
reset_follower_data() {
    local follower_id=$1
    
    echo -e "\n${BLUE}重置从节点数据: ${follower_id}${NC}"
    curl -s -X POST "http://${LEADER_HOST}:${LEADER_PORT}/admin/reset-follower/${follower_id}" | jq '.'
}

# 创建测试数据
create_test_data() {
    local host=$1
    local port=$2
    
    echo -e "\n${BLUE}在Leader节点创建测试数据:${NC}"
    
    # 创建测试目录
    curl -s -X POST "http://${host}:${port}/api/v1/meta/mkdirs" \
        -H "Content-Type: application/json" \
        -d '{"path": "/test-consistency", "permissions": 755, "owner": "test", "group": "test"}' | jq '.'
    
    # 创建测试文件
    curl -s -X POST "http://${host}:${port}/api/v1/meta/createFile" \
        -H "Content-Type: application/json" \
        -d '{"path": "/test-consistency/file1.txt", "replication": 2, "permissions": 644, "owner": "test", "group": "test"}' | jq '.'
    
    curl -s -X POST "http://${host}:${port}/api/v1/meta/createFile" \
        -H "Content-Type: application/json" \
        -d '{"path": "/test-consistency/file2.txt", "replication": 2, "permissions": 644, "owner": "test", "group": "test"}' | jq '.'
}

# 主测试流程
main() {
    print_step "1. 检查所有节点状态"
    
    if ! check_node_online $LEADER_HOST $LEADER_PORT "Leader"; then
        print_error "Leader节点不可用，测试终止"
        exit 1
    fi
    
    check_node_online $FOLLOWER1_HOST $FOLLOWER1_PORT "Follower1" || true
    check_node_online $FOLLOWER2_HOST $FOLLOWER2_PORT "Follower2" || true
    
    print_step "2. 获取各节点数据摘要"
    get_data_summary $LEADER_HOST $LEADER_PORT "Leader"
    get_data_summary $FOLLOWER1_HOST $FOLLOWER1_PORT "Follower1" || true
    get_data_summary $FOLLOWER2_HOST $FOLLOWER2_PORT "Follower2" || true
    
    print_step "3. 创建测试数据（在Leader节点）"
    create_test_data $LEADER_HOST $LEADER_PORT
    
    print_step "4. 等待数据同步"
    echo "等待5秒让数据同步到从节点..."
    sleep 5
    
    print_step "5. 再次获取各节点数据摘要"
    get_data_summary $LEADER_HOST $LEADER_PORT "Leader"
    get_data_summary $FOLLOWER1_HOST $FOLLOWER1_PORT "Follower1" || true
    get_data_summary $FOLLOWER2_HOST $FOLLOWER2_PORT "Follower2" || true
    
    print_step "6. 执行数据一致性检查"
    perform_consistency_check
    
    print_step "7. 获取集群同步状态"
    get_sync_status $LEADER_HOST $LEADER_PORT "Leader"
    
    print_step "8. 测试完成"
    print_success "数据一致性检查测试完成"
    
    echo -e "\n${YELLOW}可用的管理命令:${NC}"
    echo "1. 检查一致性: curl -X POST http://${LEADER_HOST}:${LEADER_PORT}/admin/consistency-check"
    echo "2. 重置从节点: curl -X POST http://${LEADER_HOST}:${LEADER_PORT}/admin/reset-follower/{followerId}"
    echo "3. 获取同步状态: curl http://${LEADER_HOST}:${LEADER_PORT}/admin/sync-status"
    echo "4. 获取健康状态: curl http://${LEADER_HOST}:${LEADER_PORT}/admin/health"
}

# 检查依赖
if ! command -v curl &> /dev/null; then
    print_error "curl 命令未找到，请安装 curl"
    exit 1
fi

if ! command -v jq &> /dev/null; then
    print_warning "jq 命令未找到，JSON输出将不会格式化"
    # 如果没有jq，创建一个简单的替代函数
    jq() {
        cat
    }
fi

# 运行主函数
main "$@"
